package com.spzx.product.config;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.*;

/**
 * Package: com.spzx.product.config
 *
 * @Description:
 * @Author xiongkunYang
 * @Create 2025/5/28 20:46
 */
@SpringBootConfiguration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        int processorsCount = Runtime.getRuntime().availableProcessors();
        // 设为处理器数量的两倍
        int corePoolSize = processorsCount * 2;
        // 最大线程数设为核心线程的两倍
        int maximumPoolSize = corePoolSize * 2;
        // 保持活跃时间为 60 秒
        long keepAliveTime = 60L;
        // 使用有界队列控制任务数量，大小为最大线程数的10倍
        int queueSize = maximumPoolSize * 10;

        //new ThreadPoolExecutor.CallerRunsPolicy()
        //自定义拒绝策略
        //通过短暂休眠来等待线程池中有空闲资源
        //再次将拒绝任务提交给线程池执行

        //线程会在需要时创建
        return new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(queueSize),
                Executors.defaultThreadFactory(),
                //new ThreadPoolExecutor.CallerRunsPolicy()
                //自定义拒绝策略
                (runnable, executor) -> {
                    try {
                        //通过短暂休眠来等待线程池中有空闲资源
                        Thread.sleep(200);
                    } catch (InterruptedException ignored) {
                    }
                    //再次将拒绝任务提交给线程池执行
                    executor.submit(runnable);
                }
        );
    }
}